package validators;

import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpSession;

import controllers.LocaleController;

import beans.RepositoryBeanRemote;

/**
 * @author Zsolt
 */
@ManagedBean
public class RepNameValidator2 implements Validator {

	@EJB
	private RepositoryBeanRemote rb;

	/**
	 * Description: method that validates repositoryName introduced by Admin
	 * 
	 * @author Zsolt
	 * @param FacesContext
	 *            , UIComponent, Object (contains the repName)
	 */
	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		String enteredName = (String) value;
		Pattern p = Pattern.compile("[a-zA-Z0-9]*");
		Matcher m = p.matcher(enteredName);
		boolean matchFound = m.matches();

		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(true);

		// internationalization
		LocaleController language = (LocaleController) session
				.getAttribute("language");
		String messageBundleName = "errorMessages.errors";
		if (language.getLanguage() == "ro") {
			messageBundleName += "_ro";
		} else if (language.getLanguage() == "hu") {
			messageBundleName += "_hu";
		} else if (language.getLanguage() == "de") {
			messageBundleName += "_de";
		}
		ResourceBundle messageBundle = ResourceBundle
				.getBundle(messageBundleName);
		// ////////

		if (enteredName.equals("") || (enteredName == null)) {
			FacesMessage message = new FacesMessage();
			message.setDetail(messageBundle.getString("repositoryNameEmpty"));
			message.setSummary(messageBundle.getString("repositoryNameEmpty"));
			throw new ValidatorException(message);
		} else {
			if (!matchFound) {
				FacesMessage message = new FacesMessage();
				message.setDetail(messageBundle.getString("usernameContainsUnapprovedCharacters"));
				message.setSummary(messageBundle.getString("usernameContainsUnapprovedCharacters"));
				throw new ValidatorException(message);
			} else {
				if (!(rb.existsNameInDB(enteredName))) {
					FacesMessage message = new FacesMessage();
					message.setDetail(messageBundle.getString("repositoryNameDoesntExistsInDatabase"));
					message.setSummary(messageBundle.getString("repositoryNameDoesntExistsInDatabase"));
					throw new ValidatorException(message);
				}
			}

		}
	}

}
